package by.averianov.discounta.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.stereotype.Repository;

import by.averianov.discounta.dataaccess.ProductDao;
import by.averianov.discounta.datamodel.Product;
import by.averianov.discounta.datamodel.Product_;

@Repository
public class ProductDaoImpl extends AbstractDaoImpl<Long, Product> implements ProductDao {
	
	protected ProductDaoImpl() {
		super(Product.class);
	}

	@Override
	public Long getCountNotNull() {
		CriteriaBuilder cb = getEm().getCriteriaBuilder();

		CriteriaQuery<Long> criteria = cb.createQuery(Long.class);
		Root<Product> root = criteria.from(Product.class);

		criteria.select(cb.count(root));
		criteria.where(cb.notEqual(root.get(Product_.countProduct), 0));

		TypedQuery<Long> query = getEm().createQuery(criteria);
		return query.getSingleResult();
	}
	
	@Override
	public List<Product> getAllNotNull(SingularAttribute<Product, ?> attr, boolean ascending, int startRecord, int pageSize) {
		CriteriaBuilder cb = getEm().getCriteriaBuilder();

		CriteriaQuery<Product> criteria = cb.createQuery(Product.class);
		Root<Product> root = criteria.from(Product.class);

		criteria.select(root);
		criteria.where(cb.notEqual(root.get(Product_.countProduct), 0));
		criteria.orderBy(new OrderImpl(root.get(attr), ascending));
		TypedQuery<Product> query = getEm().createQuery(criteria);
		query.setFirstResult(startRecord);
		query.setMaxResults(pageSize);

		List<Product> results = query.getResultList();
		return results;
	}

}
